<?php
/**
 * 邮件
 */

namespace app\admin\controller;

use app\common\model\EmailLog;
use app\common\model\EmailServer;
use app\common\model\SalaryLog;
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Env;
use think\facade\Log;
use think\Queue;
use think\Request;
use app\common\validate\EmailValidate;
ini_set('max_execution_time','0');
class EmailController extends Controller
{
    public $fields = ['salary_time'=>'时间','insure_id'=>'社保关系','basic_salary'=>'基本工资','manage_salary'=>'管理工资','title_salary'=>'职称工资','education_salary'=>'学历津贴','nightwork_salary'=>'夜班津贴','payscale_salary'=>'薪级工资','secret_salary'=>'保密工资','overtime_salary'=>"加班工资",'fulltime_salary'=>'全勤奖','phone_salary'=>'通讯补贴','housing_salary'=>'住房补贴','other_salary'=>'其他','total_fixed_salary'=>'固定工资合计','base_merit_salary'=>'绩效基数','merit_salary'=>'绩效','real_total_fixed_salary'=>'实际工资合计','commission'=>'提成','live_commission'=>'直播提成','bonus_penalty'=>'奖惩','late_cut'=>'迟到扣除','sick_allowance'=>'病假补助','absence_leave_cut'=>'事假扣除','absenteeism_cut'=>'旷工扣除','storage_time_cash'=>'存班折现','travel_allowance'=>'差旅补助','repair_miss_card_cut'=>'补缺卡扣除','other'=>'其他','total_payoff'=>'应发工资合计','personal_pay'=>'个户发放','real_pay'=>'实际发放','cut_cash'=>'扣款','social_security_salary'=>'社保工资','deduct_social_money'=>'社保扣除','taxable_salary'=>'计税工资','personal_tax'=>'个税','after_tax_insurance_salary'=>'税后险后工资','card_name'=>'银行卡姓名','card_num'=>'卡号','update_time'=>'修改时间','info'=>'自动计算信息','remarks'=>'备注'];

    //邮件页面
    public function email(Request $request,SalaryLog $salaryLog)
    {

        $params = $request->param();
        if (isset($params['staff_id']) && isset($params['salary_time'])){
            $this->assign([
                'staff_id'=>$params['staff_id'],
                'salary_time'=>$params['salary_time'],
            ]);
        }
        $fields = $this->fields;
        $field = config('emailField.field');
        $this->assign('field',$field);
        $this->assign('fields',$fields);
        $staff_list = $salaryLog->with(['staff'=>function($query){
            $query->field('id,name');
    }])->field('id,staff_id')->group('staff_id')->select();
        $this->assign([
            'field'=>$field,
            'fields'=>$fields,
            'staff_list'=>$staff_list
        ]);
        return $this->fetch();
    }

    //获取工资时间内的员工信息
    public function getStaffBySalaryTime(Request $request,SalaryLog $salaryLog)
    {
        $salaryTime = $request->param('salary_time');
        $time  =strtotime($salaryTime);
        $staff_list = $salaryLog->with(['staff'=>function($query){
            $query->field('id,name,email');
        }])->where(['salary_time'=>$time,'status'=>1])->select();

         return !($staff_list->isEmpty()) ? success('操作成功', URL_BACK, $staff_list) : error('没有此月份员工工资信息');

    }
    //邮件设置页面
    public function edit(Request $request)
    {
        $data = config('email.smtp');
        $this->assign('data',$data);

        if ($request->isPost()){
            $params = $request->param();
            unset($params['__token__']);
            $arr = $params;
            $url = URL_RELOAD;
            $result = $this->config_set($arr,'email','smtp');
            return $result ? success('添加成功',$url) : error();
        }
        return $this->fetch();
    }

    //发送工资字段设置
    public function edit2(Request $request)
    {

        $fields = $this->fields;
        $field = config('emailField.field');
        $this->assign('field',$field);
        $this->assign('fields',$fields);

        if ($request->isPost()){
            $params = $request->param();
           $field = $params['checkbox'];
           if (empty($field)){
               error('没有选择任何字段');
           }else{
               $url = URL_RELOAD;
                $result = $this->config_set($field,'emailField','field');
               return $result ? success('添加成功',$url) : error();
           }

        }
        return $this->fetch();
    }
    //发送邮件功能
    public function sendEmail(Request $request, EmailValidate $validate, EmailLog $emailLog,SalaryLog $salaryLog,EmailServer $emailServer)
    {

        $params = $request->param();
        $salaryTime = $request->param('salary_time');
        $time  =strtotime($salaryTime);
        $validate_result = $validate->scene('add')->check($params);
        if (!$validate_result) {
            return error($validate->getError());
        }
        //处理附件上传
        if (!empty($_FILES['file']['name'][0])) {
            $attachment_file = new \app\common\model\Attachment;
            $file = $attachment_file->uploadMulti('file');
            if ($file) {
                $params['file'] = $file;
            } else {
                return error($attachment_file->getError());
            }
        }
        if ($params['is_all']==='0' && !isset($params['staff'])){
            error('没有选择员工');exit();
        }
        if(!isset($params['checkbox'])){
            error('请选择要发送的字段');exit();
        }
        
        $field = $params['checkbox'];
        if (empty($field)) {
            error('没有选择任何字段');exit();
        }
        $field = array_merge($field,['id','staff_id','email_status']);

        if ($params['is_all'] ==='1'){
            $datas = SalaryLog::with('staff,insure')->where(['salary_time'=>$time,'email_status'=>0])->field($field)->select();
        }else{
            $datas = SalaryLog::with('staff,insure')->field($field)->where(['salary_time'=>$time,'email_status'=>0])->where('staff_id','in',$params['staff'])->select();
        }
        $files = [];
        if (!$datas->isEmpty()){
            $datas = $datas->toArray();

            if (isset($params['file'])){
                foreach ($params['file'] as $key => $value){
                    $files[] = $_SERVER["DOCUMENT_ROOT"] . $value;
                }
            }

            $fields = $this->fields;
            $address = '';
            $result = [];
            $s = 0;
            $f = 0;
            $name ='';
            $insertData = [];
            $i = 0;
            $emails = $emailServer::select();
            if ($emails->isEmpty()){
                return error('请先设置邮箱服务器');
            }else{
                $emaildatas = $emails->toArray();
                $count = count($emaildatas);
            }

            foreach ($datas as $keys => $values){
                $sendData = $params['content']."\r\n";
                $sendData .= "姓名：" . $values['staff']['name']. "<br>";
                foreach ($values as $key => &$value) {
                    if ($key ==='insure_id'){
                        $value = $values['insure']['insure'];
                    }
                    if (array_key_exists($key, $fields)) {
                        $sendData .= $fields[$key] . ':' . $value . "<br>";
                    }
                    if ($key === 'staff') {
                        $address = $value['email'];
                        $name = $value['name'];
                        if (!$address){
                            $ids = EmailLog::where(['salary_id'=>$values['id']])->column('id');
                            if (!empty($ids)){
                                $insertData[] = (['id'=>$ids['0'],'salary_id'=>$values['id'],'staff_id' => $values['staff_id'], 'salary_email_content' => $sendData, 'salary_time' => $time, 'salary_email_msg' => '邮箱不存在', 'status' => 0, 'address' => '', 'staff_name' => $name,'create_time'=>$_SERVER['REQUEST_TIME'],'update_time'=>$_SERVER['REQUEST_TIME']]);
                                continue 2;
                            }else{
                                $insertData[] = (['salary_id'=>$values['id'],'staff_id' => $values['staff_id'], 'salary_email_content' => $sendData, 'salary_time' => $time, 'salary_email_msg' => '邮箱不存在', 'status' => 0, 'address' => '', 'staff_name' => $name,'create_time'=>$_SERVER['REQUEST_TIME'],'update_time'=>$_SERVER['REQUEST_TIME']]);
                                continue 2;
                            }

                        }
                    }

                    $address = $values['staff']['email'];
                    $name = $values['staff']['name'];
                }
                $staff_id = $values['staff_id'];
                $id = $values['id'];
                $index = $i%$count;

                $senddatas = ['id'=>$id,'staff_id'=>$staff_id,'name'=>$name,'time'=>$time,'address'=>$address,'subject'=>$params['subject'],'sendData'=>$sendData,'files'=>$files,'conf'=>$emaildatas[$index]];
                $i++;
                $sendData = $params['content']."\r\n";
                $this->mailTask($senddatas);//mailTask为邮件队列
            }
            try {
                $emailLog->insertAll($insertData,true);
            } catch (\Exception $e) {
                return $e->getMessage();
            }
            return success('邮件发送任务下达，请留意邮件日志');

        }else{
            return error('没有要发送邮件或邮件已发送');
        }
    }

//    public function send($id,$staff_id,$name,$time,$address,$subject,$content,$files=[])
//    {
//
//        $config = config('email.smtp');
//        $mail   = new PHPMailer(true);                              // Passing `true` enables exceptions
//        try {
//
//
//            $full_content = $content;
//
//            //服务器配置
//            $mail->CharSet   = "UTF-8";                     //设定邮件编码
//            $mail->SMTPDebug = 0;                        // 调试模式输出
//            $mail->isSMTP();                             // 使用SMTP
//            $mail->Host       = $config['host'];                // SMTP服务器
//            $mail->SMTPAuth   = true;                      // 允许 SMTP 认证
//            $mail->Username   = $config['username'];                // SMTP 用户名  即邮箱的用户名
//            $mail->Password   = $config['password'];             // SMTP 密码  部分邮箱是授权码(例如163邮箱)
//            $mail->SMTPSecure = 'ssl';                    // 允许 TLS 或者ssl协议
//            $mail->Port       = 465;                            // 服务器端口 25 或者465 具体要看邮箱服务器支持
//
//            $mail->setFrom($config['address'], $config['name']);  //发件人
//            $mail->addAddress($address, $address);  // 收件人
//            //$mail->addAddress('ellen@example.com');  // 可添加多个收件人
//            $mail->addReplyTo($config['address'], $config['name']); //回复的时候回复给哪个邮箱 建议和发件人一致
//            //$mail->addCC('cc@example.com');                    //抄送
//            //$mail->addBCC('bcc@example.com');                    //密送
//
//            //发送附件
//            if (!empty($files)){
//                foreach ($files as $k =>$v){
//                    $mail->addAttachment($v);
//                }
//            }
//             // 发送附件并且重命名
//
//            //Content
//            $mail->isHTML(true);  // 是否以HTML文档格式发送  发送后客户端可直接显示对应HTML内容
//            $mail->Subject = $subject;
//            $mail->Body    = $full_content;
//            $mail->AltBody = $content;
//
//            $mail->send();
//            $msg    = $name.'邮件发送成功';
//            $data['status'] = 1;
//            $data['salary_id'] = $id;
//            $data['address'] = $address;
//            $data['staff_id'] = $staff_id;
//            $data['staff_name'] = $name;
//            $data['salary_time'] = $time;
////            $data['salary_email_content'] = json_encode($content,JSON_UNESCAPED_UNICODE);
//            $data['salary_email_content'] = $content;
//            $data['salary_email_msg'] = $msg;
//            $data['create_time'] = time();
//        } catch (\Exception $e) {
//            $msg    = $name.'邮件发送失败,错误信息:' . $mail->ErrorInfo;
//            $data['status'] = 0;
//            $data['salary_id'] = $id;
//            $data['address'] = $address;
//            $data['staff_id'] = $staff_id;
//            $data['staff_name'] = $name;
//            $data['salary_time'] = $time;
//            $data['salary_email_content'] = $content;
//            $data['salary_email_msg'] = $msg;
//            $data['create_time'] = time();
//        }
//        return $data;
//    }

    //邮件队列
    private function mailTask($sendDatas =[])
    {
        $jobHandlerClassName  = 'app\index\job\SendEmail';//负责处理队列任务的类
        $jobQueueName  	  = "sendEmailQueue";//队列名称
        $isPushed = Queue::push($jobHandlerClassName , $sendDatas , $jobQueueName );//将该任务推送到消息队列
        if($isPushed !== false ){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 修改扩展配置文件.
     *
     * @param array  $arr  需要更新或添加的配置
     * @param string $file 配置文件名(不需要后辍)
     *
     * @return bool
     */
    function config_set($arr = [], $file = 'dome',$name =0)
    {
        if (is_array($arr)) {
            // 文件路径
            $filepath = Env::get('config_path').$file.'.php';
            // 检测是否存在,不存在新建
            if (!file_exists($filepath)) {
                $conf = '<?php return [];';
                file_put_contents($filepath, $conf);
            }
            // 添加配置项
            $conf = include $filepath;

            foreach ($arr as $key => $value) {
                $conf[$key] = $value;
            }
            // 修改配置项
            $str = "<?php\r\nreturn [\r\n '{$name}'=>[\r\n";
            foreach ($conf as $key => $value) {
                switch (gettype($value)) {
                    case 'string':
                        $str .= "\t'$key' => '$value',"."\r\n";
                        break;
                    case 'number':
                        $str .= "\t'$key' => $value,"."\r\n";
                        break;
                    case 'boolean':
                        $str .= "\t'$key' => ".($value?'true':'false').","."\r\n";
                        break;
                    default:
                        # code...
                        break;
                }
            }
            $str .= "]\r\n];";
            // 写入文件
            return file_put_contents($filepath, $str);
        } else {
            return false;
        }
    }

}